package net.bwie.jtp.ads.udf;

import org.apache.hadoop.hive.ql.exec.UDF;
import org.lionsoul.ip2region.DbConfig;
import org.lionsoul.ip2region.DbSearcher;

import java.util.HashMap;
import java.util.Map;

/**
 * 使用Ip2Region库，将ip地址解析为地理区域信息
 * @author xuanyu
 * @date 2025/7/11
 */
public class ParseIpToRegion extends UDF {

	public Map<String, String> evaluate(String ipStr) throws Exception{
		// 定义集合
		Map<String, String> map = new HashMap<String, String>() ;

		// 1. DBSearch对象
		DbSearcher dbSearcher = new DbSearcher(
			new DbConfig(),
			//"jtp-ads-warehousoe/src/main/resources/ip2region.db"
			"/home/bwie/ip2region.db"
		);
		// 2.查找
		String region = dbSearcher.binarySearch(ipStr).getRegion();
		/*
			国家|区域|省份|城市|ISP  ->   中国|0|天津|天津市|联通
		 */
		//System.out.println(region);
		// 3.解析
		String[] split = region.split("\\|");
		map.put("country", split[0]);
		map.put("area", split[1]);
		map.put("province", split[2]);
		map.put("city", split[3]);
		map.put("isp", split[4]);

		return map ;
	}

	public static void main(String[] args) throws Exception {
		System.out.println(new ParseIpToRegion().evaluate("218.68.181.92"));
	}

}
